package com.cloudbroker.bcs.platform.ltb.middle.util;

import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserCacheFreshType;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserType;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.BrokerVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.UserVO;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.ltb.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.ltb.middle.model.UserCache;
import com.hundsun.jres.common.util.UUID;

/**
 * Created by tianrui on 2016/7/8.
 * user_token 缓存数据 userInfo + user_key + op_entrust_way + op_station + terminal_type
 */
public class UserTokenUtil {

    private final static int baleFulCount = 4;
    private final static int frezzTime = 60;

    /**
     * 新增user_token缓存
     * */
    public static String addUserToken(UserCache userCache){
        String user_token = UUID.randomUUID().toString();
        SessionHelper sessionHelper = SessionHelper.getInstance();
//        String user_token = sessionHelper.getAccess_tokenKey(user_key);
        sessionHelper.setInfoForSession(user_token, userCache.toStringInfo(),
                ConfigValues.getSessionTimeout());
        return user_token;
    }

    /**
     * 新增游客user_token缓存
     * */
    public static String addVisitorToken(UserCache userCache){
        String user_token = "visitor" + UUID.randomUUID().toString();
        SessionHelper sessionHelper = SessionHelper.getInstance();
//        String user_token = sessionHelper.getAccess_tokenKey(user_key);
        int visitor_time = 60 * 60 * 24 * 7;
        sessionHelper.setInfoForSession(user_token, userCache.toStringInfo(),
                visitor_time);
        return user_token;
    }

    /**
     * 更新user_token缓存
     * */
    public static void updateUserToken(String user_token, UserCache userCache){
        SessionHelper sessionHelper = SessionHelper.getInstance();
        sessionHelper.setInfoForSession(user_token, userCache.toStringInfo(), ConfigValues.getSessionTimeout());
    }

    /**
     * 更新user_token缓存
     * */
    public static void updateUserToken(String user_token, UserCache userCache, int valid_time){
        SessionHelper sessionHelper = SessionHelper.getInstance();
        sessionHelper.setInfoForSession(user_token, userCache.toStringInfo(), valid_time);
    }



    /**
     * 查询user_token缓存
     * */
    public static UserCache queryUserToken(String user_token){
        CacheHelper cacheHelper = CacheHelper.getInstance();
        return UserCache.fromStringInfo(cacheHelper.get(user_token));
    }


    /**
     * 删除user_token缓存
     * */
    public static void deleteUserToken(String user_token){
        SessionHelper.getInstance().delete(user_token);
    }


    /**
     * 用户缓存密码校验
     * */
    public static boolean isRightOldPassword(String user_token, String oldPassword){
        UserCache userCache = queryUserToken(user_token);
        if (null == userCache){
            return false;
        }
        UserVO user = userCache.getBrokerVO().getUser();
        if (null == user){
            return false;
        }
        if (oldPassword.equals(user.getPassword())){
            return true;
        }
        return false;
    }

    /**
     * 用户密码修改后缓存刷新
     * */
    public static <T> void updateByUpdateKey(String user_token, T update_key, UserCacheFreshType freshType){
        UserCache userCache = queryUserToken(user_token);
        if (null != userCache){
            UserVO userVO = userCache.getBrokerVO().getUser();
            switch (freshType) {
                case UPDATE_PASSWORD:
//                    userCache.getBrokerVO().getUser().setPassword((String)update_key);
                    break;
                case UPDATE_AVATAR: {
                    userVO.setAvatar(String.valueOf(update_key));
                    userCache.getBrokerVO().setUser(userVO);
                    break;
                }
                case UPDATE_ALIAS:
                    userVO.setAlias_name(String.valueOf(update_key));
                    userCache.getBrokerVO().setUser(userVO);
                    break;
                }
        }
        updateUserToken(user_token, userCache);
    }

    /**
     * 缓存后台参数设置
     * */
    public static <T extends UserVO> void setBGBrokerVO(BrokerVO bgBrokerVO, T form){
        bgBrokerVO.setCompany_id(form.getCompany_id());
        bgBrokerVO.setSendercomp_id(form.getSendercomp_id());
        bgBrokerVO.setOp_branch_no(form.getOp_branch_no());
        bgBrokerVO.setBranch_no(form.getBranch_no());
        bgBrokerVO.setPassword_type(form.getPassword_type());
        bgBrokerVO.setOperator_no(form.getOperator_no());
        bgBrokerVO.setOp_entrust_way(form.getOp_entrust_way());
        bgBrokerVO.setOp_station(form.getOp_station());
        bgBrokerVO.setTerminal_type(form.getTerminal_type());
        bgBrokerVO.setUser_key(form.getUser_key());
    }

    /**
     * 管理人员校验
     * 1.判断缓存中是否有admin数据 若有则从缓存中返回校验数据
     * 2.若缓存中不存在从数据库查询数据返回，并加入缓存
     * admin = admin + user_name + password + sendercomp_id + company_id
     * */

    public static String getAdminUserToken(String user_key){
        SessionHelper sessionHelper = SessionHelper.getInstance();
        String user_token = sessionHelper.getAdmin_token(user_key);
        return user_token;
    }

    /**
     * 管理人员登录校验
     * */
    public static boolean adminLoginVerify(String user_key, String company_id, String sendercomp_id){
        String user_token = getAdminUserToken(user_key);
        CacheHelper cacheHelper = CacheHelper.getInstance();
        if (cacheHelper.exists(user_token)){
            //存在刷新缓存
            UserCache userCache = new UserCache();
            userCache.setUser_type(String.valueOf(UserType.ADMIN.getVal()));
            BrokerVO brokerVO = new BrokerVO();
            brokerVO.setCompany_id(company_id);
            brokerVO.setSendercomp_id(sendercomp_id);
            userCache.setBrokerVO(brokerVO);
            cacheHelper.set(user_token, userCache.toStringInfo(), ConfigValues.getSessionTimeout());
            return true;
        }
        return false;
    }

    /**
     * 管理端token增加
     * */
    public static void addAdminUserToken(String user_key, String company_id, String sendercomp_id){
        String user_token = getAdminUserToken(user_key);
        addTempToken(user_token, company_id, sendercomp_id, UserType.ADMIN.getVal());
    }

    /**
     * 投顾登录时需调用后台接口 增加临时token通过校验
     * */
    public static String addTempUserToken(String company_id, String sendercomp_id){
        String user_token = UUID.randomUUID().toString();
        addTempToken(user_token, company_id, sendercomp_id, UserType.LEADER.getVal());
        return user_token;
    }

    /**
     * 发送短信调用后台接口时 增加临时token
     * */
    public static String addSMSUserToken(String company_id, String sendercomp_id){
        String user_token = "SMS" + UUID.randomUUID().toString();
        addTempToken(user_token, company_id, sendercomp_id, UserType.VISITOR.getVal());
        return user_token;
    }

    /**
     * 统一管理平台查询后台增加临时token
     * */
    public static String addPublicManageUserToken(String company_id, String sendercomp_id){
        String user_token = "PM" + UUID.randomUUID().toString();
        addTempToken(user_token, company_id, sendercomp_id, UserType.VISITOR.getVal());
        return user_token;
    }

    /**
     * 为临时token赋值
     * */
    private static void addTempToken(String user_token, String company_id, String sendercomp_id, int user_type){
        UserCache userCache = new UserCache();
        BrokerVO brokerVO = new BrokerVO();
        brokerVO.setCompany_id(company_id);
        brokerVO.setSendercomp_id(sendercomp_id);
        userCache.setUser_type(String.valueOf(user_type));
        userCache.setBrokerVO(brokerVO);
        SessionHelper sessionHelper = SessionHelper.getInstance();
        sessionHelper.setInfoForSession(user_token, userCache.toStringInfo(), ConfigValues.getSessionTimeout());
    }


    /**
     * 用户登录缓存
     * key = company + sendercomp_id + mobile + user_type
     * */
    public static boolean updatedLoginUserToken(String key){
        String accountFrezzToken = "AccFrezz" + key;
        String user_token = "baleFul" + key;
        CacheHelper cacheHelper = CacheHelper.getInstance();
        if (cacheHelper.exists(accountFrezzToken)) return true;
        String loginCount = cacheHelper.get(user_token);
        if (loginCount != null){
            int count = Integer.valueOf(loginCount).intValue();
            count += 1;
            loginCount = String.valueOf(count);
        }else {
            loginCount = "1";
        }
        //有效时长1秒
        cacheHelper.set(user_token, loginCount, 1);
        //1秒之内请求超过3次视为恶意攻击
        if (Integer.valueOf(loginCount).intValue() > baleFulCount){
            //视为恶意后此账号封闭1分钟
            cacheHelper.set(accountFrezzToken, String.valueOf(loginCount), frezzTime);
            return true;
        }else {
            return false;
        }
    }
}
